<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>专注计时器 | Focus Timer</title>
    <meta name="description" content="提高专注力的计时器工具，通过积分和等级系统激励持续专注">
    <meta name="keywords" content="专注, 计时器, 番茄工作法,  productivity, focus timer">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        dark: '#1E293B',
                        light: '#F8FAFC',
                        accent: '#8B5CF6',
                        multiplier: '#F59E0B'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-transform-opacity {
                transition-property: transform, opacity;
            }
            .timer-digit {
                @apply text-[clamp(3rem,10vw,8rem)] font-bold text-dark transition-all duration-300;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-medium py-3 px-6 rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 focus:outline-none focus:ring-2 focus:ring-primary/50;
            }
            .btn-secondary {
                @apply bg-secondary hover:bg-secondary/90 text-white font-medium py-3 px-6 rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 focus:outline-none focus:ring-2 focus:ring-secondary/50;
            }
            .btn-danger {
                @apply bg-danger hover:bg-danger/90 text-white font-medium py-3 px-6 rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 focus:outline-none focus:ring-2 focus:ring-danger/50;
            }
            .data-btn {
                @apply w-10 h-10 rounded-full flex items-center justify-center shadow-md transition-all duration-300 transform hover:-translate-y-1 focus:outline-none;
            }
            .modal-backdrop {
                @apply fixed inset-0 bg-black/50 backdrop-blur-sm z-40 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300;
            }
            .modal-backdrop.active {
                @apply opacity-100 pointer-events-auto;
            }
            .modal-content {
                @apply bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform scale-95 transition-all duration-300 opacity-0;
            }
            .modal-backdrop.active .modal-content {
                @apply scale-100 opacity-100;
            }
            .progress-bar {
                @apply h-3 bg-gray-200 rounded-full overflow-hidden;
            }
            .progress-fill {
                @apply h-full bg-accent rounded-full transition-all duration-500 ease-out;
            }
            .confirmation-modal {
                @apply fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300;
            }
            .confirmation-modal.active {
                @apply opacity-100 pointer-events-auto;
            }
            .confirmation-content {
                @apply bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 p-6 transform scale-95 transition-all duration-300 opacity-0;
            }
            .confirmation-modal.active .confirmation-content {
                @apply scale-100 opacity-100;
            }
            .toast-notification {
                @apply fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-dark text-white px-4 py-2 rounded-lg shadow-lg opacity-0 pointer-events-none transition-opacity duration-300 z-50;
            }
            .toast-notification.active {
                @apply opacity-100 pointer-events-auto;
            }
            .points-container {
                @apply flex items-center min-w-[120px];
            }
            .points-value {
                @apply text-[clamp(1.5rem,3vw,2.5rem)] font-bold min-w-[80px] text-right transition-colors duration-300;
            }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <nav class="bg-white/90 backdrop-blur-md shadow-sm sticky top-0 z-30">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-clock-o text-primary text-2xl"></i>
                <span class="text-xl font-bold text-dark">专注计时器</span>
            </div>
            <div class="hidden md:flex items-center space-x-6">
                <a href="#" class="text-gray-600 hover:text-primary transition-colors">首页</a>
                <a href="#features" class="text-gray-600 hover:text-primary transition-colors">功能</a>
                <a href="#about" class="text-gray-600 hover:text-primary transition-colors">关于</a>
            </div>
            <button class="md:hidden text-gray-600 hover:text-primary">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="flex-grow flex flex-col items-center justify-center p-4 relative">
        <!-- 简短介绍 -->
        <div class="text-center max-w-2xl mb-10">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-dark mb-4">提升专注力，高效完成任务</h1>
            <p class="text-gray-600 text-lg">通过积分和等级系统，激励自己保持专注，养成高效工作习惯</p>
        </div>
        
        <!-- 计时器显示 -->
        <div class="mb-12 text-center">
            <div id="timer" class="timer-digit">00:00:00</div>
            <div id="task-display" class="text-gray-600 mt-2 text-lg hidden">
                当前: <span id="current-task">无任务</span>
            </div>
            <div class="grid grid-cols-2 gap-2 mt-1 hidden" id="session-stats">
                <div id="current-points-display" class="text-lg">
                    本次积分: <span id="current-points" class="font-medium text-secondary">0.00</span>
                </div>
                <div id="current-exp-display" class="text-lg">
                    本次经验: <span id="current-exp" class="font-medium text-accent">0.00</span>
                </div>
            </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="flex flex-wrap gap-4 w-full max-w-2xl justify-center">
            <button id="start-stop-btn" class="btn-primary flex-1 flex items-center justify-center">
                <i class="fa fa-play mr-2"></i> 开始
            </button>
            <button id="pause-resume-btn" class="btn-secondary flex-1 flex items-center justify-center" disabled="">
                <i class="fa fa-pause mr-2"></i> 暂停
            </button>
            <button id="import-time-btn" class="btn-primary flex-1 flex items-center justify-center">
                <i class="fa fa-clock-o mr-2"></i> 导入时长
            </button>
            <button id="stats-btn" class="btn-secondary flex-1 flex items-center justify-center">
                <i class="fa fa-bar-chart mr-2"></i> 统计
            </button>
        </div>
        
        <!-- 状态栏：积分、倍率、利率和经验 -->
        <div class="w-full max-w-4xl mt-10 bg-white/80 backdrop-blur-md rounded-xl shadow-sm p-4">
            <div class="container mx-auto flex flex-wrap items-center justify-between gap-2">
                <!-- 积分显示 -->
                <div class="points-container">
                    <i class="fa fa-star text-yellow-500 text-2xl mr-2 flex-shrink-0"></i>
                    <span id="points" class="points-value text-dark">0.00</span>
                </div>
                
                <!-- 倍率和利率显示 -->
                <div class="flex flex-col sm:flex-row gap-4">
                    <div class="flex items-center">
                        <span class="text-sm font-medium text-gray-600 mr-2">倍率:</span>
                        <span id="multiplier-display" class="text-lg font-bold text-multiplier">1.00x</span>
                    </div>
                    <div class="flex items-center">
                        <span class="text-sm font-medium text-gray-600 mr-2">利率:</span>
                        <span id="interest-rate-display" class="text-lg font-bold text-green-500">0.001%</span>
                    </div>
                </div>
                
                <!-- 经验条和等级 -->
                <div class="flex flex-col items-end w-full sm:w-auto sm:flex-1 mt-2 sm:mt-0">
                    <div class="flex items-center mb-1">
                        <span class="text-sm font-medium text-gray-600 mr-2">等级: </span>
                        <span id="level" class="text-lg font-bold text-accent">1</span>
                        <span class="text-sm text-gray-500 ml-2" id="exp-text">0.00/200.00</span>
                    </div>
                    <div class="progress-bar w-full sm:w-48">
                        <div id="exp-bar" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 功能介绍 -->
        <section id="features" class="w-full max-w-4xl mt-20">
            <h2 class="text-2xl font-bold text-center mb-10">为什么选择我们的专注计时器</h2>
            <div class="grid md:grid-cols-3 gap-6">
                <div class="bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow">
                    <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mb-4">
                        <i class="fa fa-trophy text-primary text-xl"></i>
                    </div>
                    <h3 class="font-bold text-lg mb-2">积分等级系统</h3>
                    <p class="text-gray-600">完成专注任务获得积分和经验，提升等级解锁更高倍率</p>
                </div>
                <div class="bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow">
                    <div class="w-12 h-12 bg-secondary/10 rounded-full flex items-center justify-center mb-4">
                        <i class="fa fa-bar-chart text-secondary text-xl"></i>
                    </div>
                    <h3 class="font-bold text-lg mb-2">任务统计分析</h3>
                    <p class="text-gray-600">记录各任务用时比例，帮助你了解时间分配情况</p>
                </div>
                <div class="bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow">
                    <div class="w-12 h-12 bg-accent/10 rounded-full flex items-center justify-center mb-4">
                        <i class="fa fa-cloud text-accent text-xl"></i>
                    </div>
                    <h3 class="font-bold text-lg mb-2">数据管理</h3>
                    <p class="text-gray-600">支持数据导出和导入，确保你的专注记录不会丢失</p>
                </div>
            </div>
        </section>
        
        <!-- 关于我们 -->
        <section id="about" class="w-full max-w-4xl mt-20 text-center">
            <h2 class="text-2xl font-bold mb-4">关于专注计时器</h2>
            <p class="text-gray-600 max-w-2xl mx-auto">
                专注计时器是一款帮助你提高工作和学习效率的工具，基于番茄工作法和游戏化设计理念，
                通过积分和等级系统激励你保持专注，培养高效的工作习惯。所有数据存储在本地，保护你的隐私安全。
            </p>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white/80 backdrop-blur-md py-6 mt-10">
        <div class="container mx-auto px-4 text-center text-gray-600">
            <p>&copy; 2023 专注计时器 | 提升专注力，高效完成任务</p>
            <div class="flex justify-center space-x-4 mt-3">
                <a href="#" class="hover:text-primary transition-colors"><i class="fa fa-github"></i></a>
                <a href="#" class="hover:text-primary transition-colors"><i class="fa fa-twitter"></i></a>
                <a href="#" class="hover:text-primary transition-colors"><i class="fa fa-envelope"></i></a>
            </div>
        </div>
    </footer>

    <!-- 数据管理按钮 -->
    <div class="fixed bottom-6 right-6 flex gap-3 z-20">
        <button id="export-btn" class="data-btn bg-green-500 text-white hover:bg-green-600" title="导出数据">
            <i class="fa fa-download"></i>
        </button>
        <button id="import-btn" class="data-btn bg-blue-500 text-white hover:bg-blue-600" title="导入数据">
            <i class="fa fa-upload"></i>
        </button>
        <button id="clear-btn" class="data-btn bg-red-500 text-white hover:bg-red-600" title="清空数据">
            <i class="fa fa-trash"></i>
        </button>
        <input type="file" id="import-file" accept=".txt" class="hidden">
    </div>

    <!-- 提示通知 -->
    <div id="toast-notification" class="toast-notification">
        操作成功
    </div>

    <!-- 任务选择模态框 -->
    <div id="task-modal" class="modal-backdrop">
        <div class="modal-content p-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-dark">选择任务</h2>
                <button id="close-task-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div id="task-list" class="space-y-3 mb-4 max-h-60 overflow-y-auto pr-2">
                <!-- 任务项将通过JS动态添加 -->
                <div class="text-center text-gray-500 py-6">
                    暂无任务，请添加新任务
                </div>
            </div>
            
            <div class="space-y-3 mb-4">
                <input type="text" id="new-task-name" placeholder="任务名称（例如：工作、休息）" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                
                <div class="flex gap-3 items-end">
                    <div class="flex-1">
                        <label class="block text-sm text-gray-600 mb-1">每多少秒变化1个积分</label>
                        <input type="number" id="new-task-interval" min="0.1" step="0.1" value="60" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">积分变化</label>
                        <select id="new-task-value" class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                            <option value="1">+1</option>
                            <option value="-1">-1</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <button id="add-task-btn" class="w-full bg-primary/10 hover:bg-primary/20 text-primary font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                <i class="fa fa-plus mr-1"></i> 添加任务
            </button>
        </div>
    </div>

    <!-- 结算模态框 -->
    <div id="result-modal" class="modal-backdrop">
        <div class="modal-content p-6">
            <div class="text-center mb-4">
                <h2 class="text-2xl font-bold text-dark">计时结果</h2>
                <div class="w-16 h-1 bg-primary mx-auto mt-2 rounded-full"></div>
            </div>
            
            <div class="space-y-4 mb-6">
                <div class="flex justify-between py-2 border-b border-gray-100">
                    <span class="text-gray-600">任务名称:</span>
                    <span id="result-task" class="font-medium">无</span>
                </div>
                <div class="flex justify-between py-2 border-b border-gray-100">
                    <span class="text-gray-600">持续时间:</span>
                    <span id="result-duration" class="font-medium">00:00:00</span>
                </div>
                <div class="flex justify-between py-2 border-b border-gray-100">
                    <span class="text-gray-600">积分变化:</span>
                    <span id="result-points" class="font-medium text-secondary">+0.00</span>
                </div>
                <div class="flex justify-between py-2">
                    <span class="text-gray-600">获得经验:</span>
                    <span id="result-exp" class="font-medium text-accent">+0.00</span>
                </div>
            </div>
            
            <button id="close-result-modal" class="w-full btn-primary">
                完成
            </button>
        </div>
    </div>

    <!-- 导入时长模态框 -->
    <div id="import-time-modal" class="modal-backdrop">
        <div class="modal-content p-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-dark">导入任务时长</h2>
                <button id="close-import-time-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div class="space-y-4 mb-6">
                <div>
                    <label class="block text-sm text-gray-600 mb-1">选择任务</label>
                    <select id="import-task-select" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <option value="">-- 请先创建任务 --</option>
                        <!-- 任务选项将通过JS动态添加 -->
                    </select>
                    <div class="text-right mt-1">
                        <button id="go-to-create-task" class="text-sm text-primary hover:text-primary/80">
                            任务不存在？去创建
                        </button>
                    </div>
                </div>
                
                <div class="grid grid-cols-3 gap-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">小时</label>
                        <input type="number" id="import-hours" min="0" value="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">分钟</label>
                        <input type="number" id="import-minutes" min="0" max="59" value="30" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">秒</label>
                        <input type="number" id="import-seconds" min="0" max="59" value="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                </div>
                
                <div id="import-experience-container">
                    <label class="block text-sm text-gray-600 mb-1">将获得的经验</label>
                    <div id="import-experience-preview" class="w-full px-3 py-2 bg-gray-50 rounded-lg text-accent font-medium">52.80</div>
                </div>
                
                <div id="task-points-info" class="hidden">
                    <label class="block text-sm text-gray-600 mb-1">任务积分规则</label>
                    <div class="w-full px-3 py-2 bg-gray-50 rounded-lg text-gray-600">
                        每<span id="task-interval-display">60</span>秒 <span id="task-value-display">+1</span>积分
                    </div>
                </div>
            </div>
            
            <button id="confirm-import-time-btn" class="w-full btn-primary" disabled="">
                确认导入
            </button>
        </div>
    </div>

    <!-- 统计信息模态框 -->
    <div id="stats-modal" class="modal-backdrop">
        <div class="modal-content p-6 max-h-[90vh] overflow-hidden flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-dark">任务统计</h2>
                <button id="close-stats-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div id="stats-list" class="flex-grow overflow-y-auto pr-2 mb-4">
                <!-- 统计项将通过JS动态添加 -->
                <div class="text-center text-gray-500 py-6">
                    暂无统计数据
                </div>
            </div>
            
            <div class="pt-4 border-t border-gray-100">
                <div class="flex justify-between text-lg font-medium mb-2">
                    <span>总计用时:</span>
                    <span id="total-time" class="text-primary">00:00:00</span>
                </div>
                <button id="close-stats-btn" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 清空确认模态框 -->
    <div id="clear-confirmation" class="confirmation-modal">
        <div class="confirmation-content">
            <div class="text-center mb-4">
                <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <i class="fa fa-exclamation-triangle text-2xl text-red-500"></i>
                </div>
                <h3 class="text-xl font-bold text-dark">确认清空所有数据？</h3>
                <p class="text-gray-500 mt-2">此操作将删除所有任务、积分、等级和设置，且无法恢复。</p>
            </div>
            
            <div class="flex gap-3 mt-6">
                <button id="cancel-clear" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                    取消
                </button>
                <button id="confirm-clear" class="flex-1 bg-red-500 hover:bg-red-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200">
                    确认清空
                </button>
            </div>
        </div>
    </div>

    <script>
        // 应用状态管理
        const state = {
            timerRunning: false,
            timerPaused: false,
            startTime: null,
            elapsedTime: 0,
            lastSavedTime: null,
            timerInterval: null,
            currentTask: null,
            points: 0,
            multiplier: 1.00, // 倍率，初始为1.00
            level: 1,
            experience: 0, // 带小数的经验值，累计制
            experienceToNextLevel: 200, // 改进：等级所需经验增长曲线更陡峭
            tasks: [],
            projectTotalTimes: {}, // 存储每个项目的总用时（毫秒）
            sessionExperience: 0, // 本次会话获得的经验（带小数）
            sessionPoints: 0, // 本次会话获得的积分（带小数）
            lastExperienceUpdate: 0, // 上次经验更新时间，用于控制更新频率
            previousTotalExperience: 0, // 用于计算新增经验的基准值
            lastInterestCalculation: Date.now(), // 上次计算利息的时间
            interestRate: 0.001, // 初始利率（百分比/秒）
            lastPointsValue: 0, // 用于检测积分变化的基准值
            lastPointsColor: null, // 记录上一次的积分颜色状态，防止闪烁
        };

        // DOM 元素
        const elements = {
            timer: document.getElementById('timer'),
            startStopBtn: document.getElementById('start-stop-btn'),
            pauseResumeBtn: document.getElementById('pause-resume-btn'),
            pointsDisplay: document.getElementById('points'),
            multiplierDisplay: document.getElementById('multiplier-display'),
            interestRateDisplay: document.getElementById('interest-rate-display'),
            levelDisplay: document.getElementById('level'),
            expBar: document.getElementById('exp-bar'),
            expText: document.getElementById('exp-text'),
            taskModal: document.getElementById('task-modal'),
            closeTaskModal: document.getElementById('close-task-modal'),
            taskList: document.getElementById('task-list'),
            newTaskName: document.getElementById('new-task-name'),
            newTaskInterval: document.getElementById('new-task-interval'),
            newTaskValue: document.getElementById('new-task-value'),
            addTaskBtn: document.getElementById('add-task-btn'),
            resultModal: document.getElementById('result-modal'),
            closeResultModal: document.getElementById('close-result-modal'),
            resultTask: document.getElementById('result-task'),
            resultDuration: document.getElementById('result-duration'),
            resultPoints: document.getElementById('result-points'),
            resultExp: document.getElementById('result-exp'),
            taskDisplay: document.getElementById('task-display'),
            currentTaskDisplay: document.getElementById('current-task'),
            currentPointsDisplay: document.getElementById('current-points-display'),
            currentPoints: document.getElementById('current-points'),
            currentExpDisplay: document.getElementById('current-exp-display'),
            currentExp: document.getElementById('current-exp'),
            sessionStats: document.getElementById('session-stats'),
            clearBtn: document.getElementById('clear-btn'),
            importBtn: document.getElementById('import-btn'),
            exportBtn: document.getElementById('export-btn'),
            importFile: document.getElementById('import-file'),
            clearConfirmation: document.getElementById('clear-confirmation'),
            cancelClear: document.getElementById('cancel-clear'),
            confirmClear: document.getElementById('confirm-clear'),
            toastNotification: document.getElementById('toast-notification'),
            importTimeBtn: document.getElementById('import-time-btn'),
            importTimeModal: document.getElementById('import-time-modal'),
            closeImportTimeModal: document.getElementById('close-import-time-modal'),
            importTaskSelect: document.getElementById('import-task-select'),
            goToCreateTask: document.getElementById('go-to-create-task'),
            importHours: document.getElementById('import-hours'),
            importMinutes: document.getElementById('import-minutes'),
            importSeconds: document.getElementById('import-seconds'),
            importExperiencePreview: document.getElementById('import-experience-preview'),
            importExperienceContainer: document.getElementById('import-experience-container'),
            confirmImportTimeBtn: document.getElementById('confirm-import-time-btn'),
            statsBtn: document.getElementById('stats-btn'),
            statsModal: document.getElementById('stats-modal'),
            closeStatsModal: document.getElementById('close-stats-modal'),
            statsList: document.getElementById('stats-list'),
            totalTime: document.getElementById('total-time'),
            closeStatsBtn: document.getElementById('close-stats-btn'),
            taskPointsInfo: document.getElementById('task-points-info'),
            taskIntervalDisplay: document.getElementById('task-interval-display'),
            taskValueDisplay: document.getElementById('task-value-display')
        };

        // 显示提示消息
        function showToast(message, duration = 3000) {
            const toast = elements.toastNotification;
            toast.textContent = message;
            toast.classList.add('active');
            
            setTimeout(() => {
                toast.classList.remove('active');
            }, duration);
        }

        // 格式化时间（毫秒 -> HH:MM:SS）
        function formatTime(ms) {
            const totalSeconds = Math.floor(ms / 1000);
            const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
            const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
            const seconds = (totalSeconds % 60).toString().padStart(2, '0');
            return `${hours}:${minutes}:${seconds}`;
        }

        // 格式化长时间（毫秒 -> 更易读的格式）
        function formatLongTime(ms) {
            const totalSeconds = Math.floor(ms / 1000);
            const days = Math.floor(totalSeconds / 86400);
            const hours = Math.floor((totalSeconds % 86400) / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            
            let result = [];
            if (days > 0) result.push(`${days}天`);
            if (hours > 0) result.push(`${hours}时`);
            if (minutes > 0) result.push(`${minutes}分`);
            
            return result.length > 0 ? result.join(' ') : '少于1分钟';
        }

        // 格式化积分显示，确保始终保留两位小数
        function formatPoints(points) {
            return points.toFixed(2);
        }

        // 统一更新积分颜色的函数，只有当颜色需要变化时才更新
        function updatePointsColor(isNegative) {
            // 只有当颜色状态改变时才更新DOM，避免闪烁
            if (isNegative !== state.lastPointsColor) {
                elements.pointsDisplay.classList.toggle('text-danger', isNegative);
                elements.pointsDisplay.classList.toggle('text-dark', !isNegative);
                state.lastPointsColor = isNegative; // 记录当前颜色状态
            }
        }

        // 格式化经验显示，保留两位小数
        function formatExperience(exp) {
            return exp.toFixed(2);
        }

        // 格式化倍率显示，保留两位小数
        function formatMultiplier(multiplier) {
            return multiplier.toFixed(2) + 'x';
        }

        // 格式化利率显示，保留三位小数百分比
        function formatInterestRate(rate) {
            return (rate * 100).toFixed(3) + '%';
        }

        // 计算当前任务获得的积分 - 实时更新，应用倍率（仅对正积分）
        function calculateCurrentPoints() {
            if (!state.currentTask) return 0;
            const totalSeconds = state.elapsedTime / 1000; // 使用精确的秒数，包括小数
            let basePoints = (totalSeconds / state.currentTask.interval) * state.currentTask.value;
            
            // 只有正积分才应用倍率
            if (state.currentTask.value > 0) {
                basePoints *= state.multiplier;
            }
            
            return basePoints;
        }

        // 根据时长（毫秒）计算经验值
        function calculateExperienceForDuration(durationMs) {
            const minutes = durationMs / (1000 * 60); // 转换为分钟
            // 精确计算经验值，确保不会出现累积错误
            return Math.round(Math.pow(minutes, 1.5) * 6 * state.multiplier * 100) / 100;
        }

        // 更新计时器和实时统计数据
        function updateTimer() {
            if (state.timerRunning && !state.timerPaused) {
                const now = Date.now();
                state.elapsedTime = now - state.startTime;
                
                // 计算并更新当前积分
                const currentPoints = calculateCurrentPoints();
                state.sessionPoints = currentPoints;
                
                // 实时更新左上角总积分
                const totalPoints = state.points + currentPoints;
                elements.pointsDisplay.textContent = formatPoints(totalPoints);
                
                // 仅当总积分<0时才显示红色，且只在状态变化时更新
                updatePointsColor(totalPoints < 0);
                
                // 更新本次积分显示
                elements.currentPoints.textContent = formatPoints(currentPoints);
                elements.currentPoints.className = currentPoints >= 0 ? 'font-medium text-secondary' : 'font-medium text-danger';
                
                // 对于+1积分的任务，实时计算并更新经验（控制更新频率）
                if (state.currentTask && state.currentTask.value > 0 && 
                    (now - state.lastExperienceUpdate > 1000)) { // 每秒最多更新一次
                    state.lastExperienceUpdate = now;
                    updateRealTimeExperience();
                }
                
                // 定期保存状态
                saveState();
            }
            elements.timer.textContent = formatTime(state.elapsedTime);
        }

        /**
         * 经验增长公式：
         * experience = (minutes^1.5) * 6 * multiplier
         * 其中minutes是专注时间（分钟）
         */
        function calculateExperience(minutes) {
            return Math.pow(minutes, 1.5) * 6;
        }

        // 实时更新经验值（应用倍率）
        function updateRealTimeExperience() {
            if (!state.currentTask || state.currentTask.value <= 0) return;
            
            const totalSeconds = state.elapsedTime / 1000; // 使用精确的秒数
            const minutes = totalSeconds / 60; // 转换为分钟
            
            // 应用经验计算公式并乘以倍率
            const baseExperience = calculateExperience(minutes) * state.multiplier;
            
            // 计算与上次相比新增的经验（保留两位小数）
            let newExperience = baseExperience - state.previousTotalExperience;
            
            // 仅当变化足够明显时才更新
            if (newExperience > 0.01) {
                // 四舍五入到两位小数
                newExperience = Math.round(newExperience * 100) / 100;
                
                state.sessionExperience += newExperience;
                state.previousTotalExperience = baseExperience;
                addExperience(newExperience);
                
                // 更新本次经验显示
                elements.currentExp.textContent = formatExperience(state.sessionExperience);
            }
        }

        // 计算并应用积分利息 - 专注时不计算
        function calculateAndApplyInterest() {
            // 关键改进：专注计时时（timerRunning且未暂停）不计算利率
            if (state.timerRunning && !state.timerPaused) {
                return;
            }
            
            const now = Date.now();
            const timePassed = now - state.lastInterestCalculation; // 毫秒
            const secondsPassed = timePassed / 1000;
            
            // 每1秒计算一次利息，确保稳定
            if (secondsPassed >= 1) { 
                let interest = 0;
                let pointsChanged = false;
                
                if (state.points >= 0) {
                    // 正积分：按当前利率计算利息，确保稳定
                    interest = state.points * (state.interestRate / 100) * secondsPassed;
                    if (Math.abs(interest) > 0.001) { // 只有明显变化时才更新
                        state.points = Math.round((state.points + interest) * 100) / 100;
                        pointsChanged = true;
                    }
                } else {
                    // 负积分：固定利率，欠债越多扣得越多
                    const debt = Math.abs(state.points);
                    // 固定利率0.005%每秒，但随债务增加而加速
                    interest = -debt * (0.005 / 100) * Math.sqrt(debt) * secondsPassed;
                    
                    if (Math.abs(interest) > 0.001) { // 只有明显变化时才更新
                        state.points = Math.round((state.points + interest) * 100) / 100;
                        pointsChanged = true;
                        
                        // 负积分时扣除经验
                        const expToDeduct = Math.min(
                            Math.round((debt * 0.0001 * secondsPassed) * 100) / 100, // 欠债越多扣越多
                            state.experience // 但不能扣到0以下
                        );
                        
                        if (expToDeduct > 0) {
                            addExperience(-expToDeduct);
                        }
                    }
                }
                
                // 如果积分有变化，更新显示
                if (pointsChanged) {
                    elements.pointsDisplay.textContent = formatPoints(state.points);
                    // 更新颜色：只有总积分<0时才显示红色
                    updatePointsColor(state.points < 0);
                }
                
                // 更新上次计算时间
                state.lastInterestCalculation = now;
                
                // 保存状态
                saveState();
            }
        }

        // 启动计时器
        function startTimer() {
            state.timerRunning = true;
            state.timerPaused = false;
            state.startTime = Date.now() - state.elapsedTime;
            state.lastSavedTime = Date.now();
            state.lastExperienceUpdate = Date.now();
            state.sessionExperience = 0; // 重置本次会话获得的经验
            state.sessionPoints = 0; // 重置本次会话获得的积分
            state.previousTotalExperience = 0; // 重置经验计算基准
            state.timerInterval = setInterval(updateTimer, 500); // 每500ms更新一次
            
            // 更新UI
            elements.startStopBtn.innerHTML = '<i class="fa fa-stop mr-2"></i> 结束';
            elements.startStopBtn.classList.remove('btn-primary');
            elements.startStopBtn.classList.add('btn-danger');
            elements.pauseResumeBtn.disabled = false;
            
            // 显示当前任务和实时统计
            elements.taskDisplay.classList.remove('hidden');
            elements.currentTaskDisplay.textContent = state.currentTask.name;
            elements.sessionStats.classList.remove('hidden');
            
            // 保存状态
            saveState();
        }

        // 暂停计时器
        function pauseTimer() {
            if (state.timerRunning && !state.timerPaused) {
                state.timerPaused = true;
                clearInterval(state.timerInterval);
                elements.pauseResumeBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 继续';
                elements.pauseResumeBtn.classList.remove('btn-secondary');
                elements.pauseResumeBtn.classList.add('btn-primary');
            } else if (state.timerRunning && state.timerPaused) {
                state.timerPaused = false;
                state.startTime = Date.now() - state.elapsedTime;
                state.lastSavedTime = Date.now();
                state.lastExperienceUpdate = Date.now();
                state.timerInterval = setInterval(updateTimer, 500);
                elements.pauseResumeBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';
                elements.pauseResumeBtn.classList.remove('btn-primary');
                elements.pauseResumeBtn.classList.add('btn-secondary');
            }
            
            // 保存状态
            saveState();
        }

        // 停止计时器并显示结果
        function stopTimer() {
            clearInterval(state.timerInterval);
            
            // 计算最终积分变化
            const pointsEarned = calculateCurrentPoints();
            state.points += pointsEarned;
            state.points = Math.round(state.points * 100) / 100; // 四舍五入保留两位小数
            
            // 更新UI显示
            elements.pointsDisplay.textContent = formatPoints(state.points);
            // 更新颜色：只有总积分<0时才显示红色
            updatePointsColor(state.points < 0);
            
            // 获得的总经验
            const expEarned = state.sessionExperience || 0;
            
            // 更新项目总用时统计
            if (state.currentTask && state.currentTask.name) {
                const taskName = state.currentTask.name;
                if (!state.projectTotalTimes[taskName]) {
                    state.projectTotalTimes[taskName] = 0;
                }
                state.projectTotalTimes[taskName] += state.elapsedTime;
            }
            
            // 显示结果模态框
            elements.resultTask.textContent = state.currentTask.name;
            elements.resultDuration.textContent = formatTime(state.elapsedTime);
            elements.resultPoints.textContent = pointsEarned >= 0 ? `+${formatPoints(pointsEarned)}` : formatPoints(pointsEarned);
            elements.resultPoints.className = pointsEarned >= 0 ? 'font-medium text-secondary' : 'font-medium text-danger';
            elements.resultExp.textContent = `+${formatExperience(expEarned)}`;
            
            openModal(elements.resultModal);
            
            // 重置状态
            resetTimer();
        }

        // 重置计时器
        function resetTimer() {
            state.timerRunning = false;
            state.timerPaused = false;
            state.elapsedTime = 0;
            state.startTime = null;
            state.lastSavedTime = null;
            state.lastExperienceUpdate = 0;
            state.previousTotalExperience = 0;
            state.currentTask = null;
            state.sessionExperience = 0;
            state.sessionPoints = 0;
            
            // 更新UI
            updateTimer();
            elements.startStopBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 开始';
            elements.startStopBtn.classList.remove('btn-danger');
            elements.startStopBtn.classList.add('btn-primary');
            elements.pauseResumeBtn.disabled = true;
            elements.pauseResumeBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';
            elements.pauseResumeBtn.classList.remove('btn-primary');
            elements.pauseResumeBtn.classList.add('btn-secondary');
            elements.taskDisplay.classList.add('hidden');
            elements.sessionStats.classList.add('hidden');
            elements.currentExp.textContent = "0.00";
            elements.currentPoints.textContent = "0.00";
            
            // 保存状态
            saveState();
        }

        /**
         * 等级系统：
         * - 升级所需经验 = 200 * (1.5)^(等级-1)
         * - 每升一级，倍率自动增加0.02
         * - 每升5级，利率增加0.0005%
         * - 经验值累计制
         */
        function addExperience(amount) {
            // 确保经验不会小于0
            if (state.experience + amount < 0) {
                amount = -state.experience; // 最多只能扣到0
            }
            
            const newExperience = amount;
            state.experience += newExperience;
            
            // 计算当前等级所需的经验值
            state.experienceToNextLevel = 200 * Math.pow(1.5, state.level - 1);
            
            // 检查是否可以升级
            while (state.experience >= state.experienceToNextLevel) {
                // 计算超出的经验值（累计制核心）
                const excessExperience = state.experience - state.experienceToNextLevel;
                
                // 升级处理
                state.level += 1;
                state.experience = excessExperience; // 保留超出部分的经验
                
                // 等级提升时自动增加倍率（保留两位小数）
                state.multiplier = Math.round((state.multiplier + 0.02) * 100) / 100;
                elements.multiplierDisplay.textContent = formatMultiplier(state.multiplier);
                
                // 每升5级，增加利率
                if (state.level % 5 === 0) {
                    state.interestRate = Math.round((state.interestRate + 0.0005) * 10000) / 10000;
                    elements.interestRateDisplay.textContent = formatInterestRate(state.interestRate);
                    showToast(`利率提升至${formatInterestRate(state.interestRate)}`);
                }
                
                // 升级动画效果
                elements.levelDisplay.classList.add('scale-150', 'text-accent');
                setTimeout(() => {
                    elements.levelDisplay.classList.remove('scale-150', 'text-accent');
                }, 500);
                
                showToast(`恭喜升级到${state.level}级！倍率提升至${formatMultiplier(state.multiplier)}`);
            }
            
            // 更新经验条显示
            const expPercentage = Math.min(100, (state.experience / state.experienceToNextLevel) * 100);
            elements.expBar.style.width = `${expPercentage}%`;
            elements.levelDisplay.textContent = state.level;
            elements.expText.textContent = `${formatExperience(state.experience)}/${formatExperience(state.experienceToNextLevel)}`;
            
            // 保存状态
            saveState();
        }

        // 渲染任务列表
        function renderTasks() {
            elements.taskList.innerHTML = '';
            updateImportTaskSelect(); // 同时更新导入时长的任务选择框
            
            if (state.tasks.length === 0) {
                // 显示空任务提示
                const emptyMsg = document.createElement('div');
                emptyMsg.className = 'text-center text-gray-500 py-6';
                emptyMsg.textContent = '暂无任务，请添加新任务';
                elements.taskList.appendChild(emptyMsg);
                return;
            }
            
            state.tasks.forEach(task => {
                const taskEl = document.createElement('div');
                taskEl.className = 'flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors duration-200';
                
                const taskInfo = document.createElement('div');
                taskInfo.className = 'flex-1';
                
                const taskName = document.createElement('div');
                taskName.className = 'font-medium';
                taskName.textContent = task.name;
                
                const taskDetails = document.createElement('div');
                taskDetails.className = `text-sm ${task.value > 0 ? 'text-secondary' : 'text-danger'}`;
                taskDetails.textContent = `每${task.interval}秒 ${task.value > 0 ? '+' : ''}${task.value}积分`;
                
                // 显示任务总用时
                if (state.projectTotalTimes[task.name]) {
                    const taskTime = document.createElement('div');
                    taskTime.className = 'text-xs text-gray-500 mt-1';
                    taskTime.textContent = `总用时: ${formatLongTime(state.projectTotalTimes[task.name])}`;
                    taskInfo.appendChild(taskTime);
                }
                
                taskInfo.appendChild(taskName);
                taskInfo.appendChild(taskDetails);
                
                const taskActions = document.createElement('div');
                taskActions.className = 'flex items-center gap-2';
                
                const selectBtn = document.createElement('button');
                selectBtn.className = 'text-primary hover:text-primary/80';
                selectBtn.innerHTML = '<i class="fa fa-check"></i>';
                selectBtn.addEventListener('click', () => {
                    state.currentTask = task;
                    closeModal(elements.taskModal);
                    startTimer();
                });
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'text-gray-400 hover:text-danger';
                deleteBtn.innerHTML = '<i class="fa fa-trash"></i>';
                deleteBtn.addEventListener('click', () => {
                    state.tasks = state.tasks.filter(t => t.id !== task.id);
                    // 同时删除该任务的统计数据
                    delete state.projectTotalTimes[task.name];
                    renderTasks();
                    renderStats();
                    saveState(); // 保存任务列表变更
                    showToast('任务已删除');
                });

                
                taskActions.appendChild(selectBtn);
                taskActions.appendChild(deleteBtn);
                
                taskEl.appendChild(taskInfo);
                taskEl.appendChild(taskActions);
                
                elements.taskList.appendChild(taskEl);
            });
        }

        // 更新导入时长的任务选择框
        function updateImportTaskSelect() {
            const select = elements.importTaskSelect;
            select.innerHTML = '';
            
            if (state.tasks.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '-- 请先创建任务 --';
                option.selected = true;
                select.appendChild(option);
                elements.confirmImportTimeBtn.disabled = true;
                elements.taskPointsInfo.classList.add('hidden');
                elements.importExperienceContainer.classList.add('hidden');
                return;
            }
            
            // 添加任务选项
            state.tasks.forEach(task => {
                const option = document.createElement('option');
                option.value = task.id;
                option.textContent = task.name;
                select.appendChild(option);
            });
            
            // 启用按钮
            elements.confirmImportTimeBtn.disabled = false;
            
            // 显示第一个任务的积分规则和经验预览（如果是正积分任务）
            if (state.tasks.length > 0) {
                showTaskPointsInfo(state.tasks[0]);
                
                // 只有正积分任务才显示经验预览
                if (state.tasks[0].value > 0) {
                    elements.importExperienceContainer.classList.remove('hidden');
                } else {
                    elements.importExperienceContainer.classList.add('hidden');
                }
            }
            
            // 更新经验预览
            updateImportExperiencePreview();
        }

        // 显示任务的积分规则信息
        function showTaskPointsInfo(task) {
            elements.taskPointsInfo.classList.remove('hidden');
            elements.taskIntervalDisplay.textContent = task.interval;
            elements.taskValueDisplay.textContent = task.value > 0 ? `+${task.value}` : task.value;
        }

        // 渲染统计信息
        function renderStats() {
            elements.statsList.innerHTML = '';
            
            const taskNames = Object.keys(state.projectTotalTimes);
            
            if (taskNames.length === 0) {
                // 显示空统计提示
                const emptyMsg = document.createElement('div');
                emptyMsg.className = 'text-center text-gray-500 py-6';
                emptyMsg.textContent = '暂无统计数据';
                elements.statsList.appendChild(emptyMsg);
                
                // 更新总时间
                elements.totalTime.textContent = '00:00:00';
                return;
            }
            
            // 计算总时间
            let totalTimeMs = 0;
            taskNames.forEach(name => {
                totalTimeMs += state.projectTotalTimes[name];
            });
            elements.totalTime.textContent = formatTime(totalTimeMs);
            
            // 按用时排序（从多到少）
            taskNames.sort((a, b) => state.projectTotalTimes[b] - state.projectTotalTimes[a]);
            
            // 渲染每个任务的统计信息
            taskNames.forEach(name => {
                const timeMs = state.projectTotalTimes[name];
                const percentage = ((timeMs / totalTimeMs) * 100).toFixed(1);
                
                const statEl = document.createElement('div');
                statEl.className = 'mb-4 pb-4 border-b border-gray-100 last:border-0 last:mb-0 last:pb-0';
                
                const taskName = document.createElement('div');
                taskName.className = 'font-medium mb-1';
                taskName.textContent = name;
                
                const timeInfo = document.createElement('div');
                timeInfo.className = 'text-sm text-gray-600 mb-2';
                timeInfo.textContent = `总用时: ${formatLongTime(timeMs)} (${percentage}%)`;
                
                const progressContainer = document.createElement('div');
                progressContainer.className = 'w-full bg-gray-100 rounded-full h-2';
                
                const progressBar = document.createElement('div');
                progressBar.className = 'bg-primary h-2 rounded-full';
                progressBar.style.width = `${percentage}%`;
                
                progressContainer.appendChild(progressBar);
                statEl.appendChild(taskName);
                statEl.appendChild(timeInfo);
                statEl.appendChild(progressContainer);
                
                elements.statsList.appendChild(statEl);
            });
        }

        // 添加新任务
        function addTask() {
            const name = elements.newTaskName.value.trim();
            const interval = parseFloat(elements.newTaskInterval.value);
            const value = parseInt(elements.newTaskValue.value);
            
            if (name && !isNaN(interval) && interval >= 0.1) {
                // 检查任务名称是否已存在
                const taskExists = state.tasks.some(task => task.name === name);
                if (taskExists) {
                    showToast('该任务名称已存在');
                    return;
                }
                
                const newTask = {
                    id: Date.now(), // 使用时间戳作为唯一ID
                    name: name,
                    interval: interval, // 允许小数秒数
                    value: value // 积分变化值 (+1 或 -1)
                };
                
                state.tasks.push(newTask);
                renderTasks();
                
                // 清空输入框
                elements.newTaskName.value = '';
                
                // 保存状态
                saveState();
                showToast('任务已添加');
            } else {
                showToast('请输入有效的任务信息');
            }
        }

        // 验证导入时长的输入值
        function validateImportTimeInputs() {
            // 验证小时
            let hours = parseInt(elements.importHours.value) || 0;
            hours = Math.max(0, hours);
            elements.importHours.value = hours;
            
            // 验证分钟
            let minutes = parseInt(elements.importMinutes.value) || 0;
            minutes = Math.max(0, Math.min(59, minutes));
            elements.importMinutes.value = minutes;
            
            // 验证秒
            let seconds = parseInt(elements.importSeconds.value) || 0;
            seconds = Math.max(0, Math.min(59, seconds));
            elements.importSeconds.value = seconds;
            
            return { hours, minutes, seconds };
        }

        // 导入任务时长
        function importTaskTime() {
            // 验证输入
            const { hours, minutes, seconds } = validateImportTimeInputs();
            
            const taskId = elements.importTaskSelect.value;
            
            if (!taskId) {
                showToast('请选择一个任务');
                return;
            }
            
            const totalSeconds = hours * 3600 + minutes * 60 + seconds;
            if (totalSeconds <= 0) {
                showToast('请输入有效的时长');
                return;
            }
            
            // 查找选中的任务
            const task = state.tasks.find(t => t.id.toString() === taskId);
            if (!task) {
                showToast('所选任务不存在');
                return;
            }
            
            const durationMs = totalSeconds * 1000;
            
            // 计算经验值
            const experienceEarned = calculateExperienceForDuration(durationMs);
            
            // 计算积分变化
            // 如果是扣积分的任务（value < 0），则积分变化为正常计算
            let pointsEarned = Math.round((totalSeconds / task.interval) * task.value * state.multiplier * 100) / 100;
            
            // 更新积分
            state.points = Math.round((state.points + pointsEarned) * 100) / 100;
            elements.pointsDisplay.textContent = formatPoints(state.points);
            // 更新颜色：只有总积分<0时才显示红色
            updatePointsColor(state.points < 0);
            
            // 更新项目总用时统计
            if (!state.projectTotalTimes[task.name]) {
                state.projectTotalTimes[task.name] = 0;
            }
            state.projectTotalTimes[task.name] += durationMs;
            
            // 添加经验
            if (task.value > 0) addExperience(experienceEarned);
            
            // 关闭模态框并显示提示
            closeModal(elements.importTimeModal);
            
            // 根据任务类型显示不同的提示信息
            if (task.value > 0) {
                showToast(`成功导入 ${task.name} 的时长 ${formatTime(durationMs)}，获得 ${formatExperience(experienceEarned)} 经验和 ${formatPoints(pointsEarned)} 积分`);
            } else {
                showToast(`成功导入 ${task.name} 的时长 ${formatTime(durationMs)}，扣除 ${formatPoints(-pointsEarned)} 积分`);
            }
            
            // 重新渲染统计
            renderStats();
            
            // 保存状态
            saveState();
        }

        // 更新导入时长的经验预览
        function updateImportExperiencePreview() {
            // 先验证输入
            validateImportTimeInputs();
            
            const taskId = elements.importTaskSelect.value;
            if (!taskId) {
                elements.importExperiencePreview.textContent = '0.00';
                return;
            }
            
            const task = state.tasks.find(t => t.id.toString() === taskId);
            if (!task) {
                elements.importExperiencePreview.textContent = '0.00';
                return;
            }
            
            // 只有正积分任务才计算和显示经验预览
            if (task.value > 0) {
                const hours = parseInt(elements.importHours.value) || 0;
                const minutes = parseInt(elements.importMinutes.value) || 0;
                const seconds = parseInt(elements.importSeconds.value) || 0;
                
                const totalSeconds = hours * 3600 + minutes * 60 + seconds;
                const durationMs = totalSeconds * 1000;
                
                const experience = calculateExperienceForDuration(durationMs);
                elements.importExperiencePreview.textContent = formatExperience(experience);
            }
        }

        // 打开模态框
        function openModal(modal) {
            modal.classList.add('active');
        }

        // 关闭模态框
        function closeModal(modal) {
            modal.classList.remove('active');
        }

        // 保存状态到localStorage
        function saveState() {
            try {
                // 创建可序列化的状态对象
                const stateToSave = {
                    timerRunning: state.timerRunning,
                    timerPaused: state.timerPaused,
                    elapsedTime: state.elapsedTime,
                    lastSavedTime: state.lastSavedTime,
                    currentTask: state.currentTask,
                    points: state.points,
                    multiplier: state.multiplier,
                    level: state.level,
                    experience: state.experience,
                    experienceToNextLevel: state.experienceToNextLevel,
                    tasks: state.tasks,
                    projectTotalTimes: state.projectTotalTimes,
                    sessionExperience: state.sessionExperience,
                    sessionPoints: state.sessionPoints,
                    previousTotalExperience: state.previousTotalExperience,
                    lastInterestCalculation: state.lastInterestCalculation,
                    interestRate: state.interestRate,
                    lastPointsValue: state.lastPointsValue,
                    lastPointsColor: state.lastPointsColor // 保存最后一次颜色状态
                };
                
                localStorage.setItem('timerAppState', JSON.stringify(stateToSave));
                return true;
            } catch (error) {
                console.error('保存状态失败:', error);
                showToast('保存数据失败');
                return false;
            }
        }

        // 从localStorage加载状态
        function loadState() {
            try {
                const savedState = localStorage.getItem('timerAppState');
                if (savedState) {
                    const parsedState = JSON.parse(savedState);
                    
                    // 恢复基本状态
                    state.points = parsedState.points || 0;
                    state.multiplier = parsedState.multiplier || 1.00;
                    state.level = parsedState.level || 1;
                    state.experience = parsedState.experience || 0;
                    state.experienceToNextLevel = parsedState.experienceToNextLevel || 200;
                    state.tasks = parsedState.tasks || state.tasks;
                    state.projectTotalTimes = parsedState.projectTotalTimes || {};
                    state.sessionExperience = parsedState.sessionExperience || 0;
                    state.sessionPoints = parsedState.sessionPoints || 0;
                    state.previousTotalExperience = parsedState.previousTotalExperience || 0;
                    state.lastInterestCalculation = parsedState.lastInterestCalculation || Date.now();
                    state.interestRate = parsedState.interestRate || 0.001;
                    state.lastPointsValue = parsedState.lastPointsValue || 0;
                    state.lastPointsColor = parsedState.lastPointsColor !== undefined ? parsedState.lastPointsColor : null;
                    
                    // 恢复计时器状态
                    state.timerRunning = parsedState.timerRunning || false;
                    state.timerPaused = parsedState.timerPaused || false;
                    state.currentTask = parsedState.currentTask || null;
                    
                    // 更新倍率和利率显示
                    elements.multiplierDisplay.textContent = formatMultiplier(state.multiplier);
                    elements.interestRateDisplay.textContent = formatInterestRate(state.interestRate);
                    
                    // 处理正在进行的计时
                    if (state.timerRunning && !state.timerPaused && parsedState.lastSavedTime) {
                        // 计算页面关闭期间经过的时间
                        const timePassedWhileClosed = Date.now() - parsedState.lastSavedTime;
                        state.elapsedTime = parsedState.elapsedTime + timePassedWhileClosed;
                        state.startTime = Date.now() - state.elapsedTime;
                        state.lastSavedTime = Date.now();
                        state.lastExperienceUpdate = Date.now();
                        
                        // 启动计时器
                        state.timerInterval = setInterval(updateTimer, 500);
                        
                        // 更新UI以反映正在运行的状态
                        elements.startStopBtn.innerHTML = '<i class="fa fa-stop mr-2"></i> 结束';
                        elements.startStopBtn.classList.remove('btn-primary');
                        elements.startStopBtn.classList.add('btn-danger');
                        elements.pauseResumeBtn.disabled = false;
                        
                        // 显示当前任务和实时统计
                        if (state.currentTask) {
                            elements.taskDisplay.classList.remove('hidden');
                            elements.currentTaskDisplay.textContent = state.currentTask.name;
                            elements.sessionStats.classList.remove('hidden');
                            elements.currentPoints.textContent = formatPoints(calculateCurrentPoints());
                            elements.currentExp.textContent = formatExperience(state.sessionExperience);
                            elements.pointsDisplay.textContent = formatPoints(state.points + state.sessionPoints);
                            // 更新颜色：只有总积分<0时才显示红色
                            updatePointsColor((state.points + state.sessionPoints) < 0);
                        }
                    } else if (state.timerPaused) {
                        // 恢复暂停状态
                        state.elapsedTime = parsedState.elapsedTime || 0;
                        
                        // 更新UI以反映暂停状态
                        elements.startStopBtn.innerHTML = '<i class="fa fa-stop mr-2"></i> 结束';
                        elements.startStopBtn.classList.remove('btn-primary');
                        elements.startStopBtn.classList.add('btn-danger');
                        elements.pauseResumeBtn.disabled = false;
                        elements.pauseResumeBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 继续';
                        elements.pauseResumeBtn.classList.remove('btn-secondary');
                        elements.pauseResumeBtn.classList.add('btn-primary');
                        
                        // 显示当前任务和实时统计
                        if (state.currentTask) {
                            elements.taskDisplay.classList.remove('hidden');
                            elements.currentTaskDisplay.textContent = state.currentTask.name;
                            elements.sessionStats.classList.remove('hidden');
                            elements.currentPoints.textContent = formatPoints(calculateCurrentPoints());
                            elements.currentExp.textContent = formatExperience(state.sessionExperience);
                            elements.pointsDisplay.textContent = formatPoints(state.points + state.sessionPoints);
                            // 更新颜色：只有总积分<0时才显示红色
                            updatePointsColor((state.points + state.sessionPoints) < 0);
                        }
                    } else {
                        // 重置状态
                        state.elapsedTime = 0;
                    }
                    
                    // 更新显示
                    elements.pointsDisplay.textContent = formatPoints(state.points);
                    // 更新颜色：只有总积分<0时才显示红色
                    updatePointsColor(state.points < 0);
                    
                    const expPercentage = Math.min(100, (state.experience / state.experienceToNextLevel) * 100);
                    elements.expBar.style.width = `${expPercentage}%`;
                    elements.levelDisplay.textContent = state.level;
                    elements.expText.textContent = `${formatExperience(state.experience)}/${formatExperience(state.experienceToNextLevel)}`;
                    updateTimer();
                    
                    // 渲染统计数据和任务选择框
                    renderStats();
                    updateImportTaskSelect();
                }
            } catch (error) {
                console.error('加载状态失败:', error);
                showToast('加载数据失败，使用默认设置');
                // 重置为初始状态
                resetToInitialState();
            }
        }

        // 重置为初始状态
        function resetToInitialState() {
            state.timerRunning = false;
            state.timerPaused = false;
            state.elapsedTime = 0;
            state.startTime = null;
            state.lastSavedTime = null;
            state.lastExperienceUpdate = 0;
            state.previousTotalExperience = 0;
            state.currentTask = null;
            state.points = 0;
            state.multiplier = 1.00;
            state.level = 1;
            state.experience = 0;
            state.experienceToNextLevel = 200;
            state.tasks = [];
            state.projectTotalTimes = {};
            state.sessionExperience = 0;
            state.sessionPoints = 0;
            state.lastInterestCalculation = Date.now();
            state.interestRate = 0.001;
            state.lastPointsValue = 0;
            state.lastPointsColor = null;
            
            // 更新UI
            elements.multiplierDisplay.textContent = formatMultiplier(state.multiplier);
            elements.interestRateDisplay.textContent = formatInterestRate(state.interestRate);
            updateTimer();
            elements.pointsDisplay.textContent = formatPoints(state.points);
            // 更新颜色：只有总积分<0时才显示红色
            updatePointsColor(state.points < 0);
            
            elements.expBar.style.width = '0%';
            elements.levelDisplay.textContent = state.level;
            elements.expText.textContent = '0.00/200.00';
            elements.currentExp.textContent = "0.00";
            elements.currentPoints.textContent = "0.00";
            
            // 渲染统计数据和任务选择框
            renderStats();
            updateImportTaskSelect();
        }

        // 清空所有数据
        function clearAllData() {
            try {
                // 停止计时器
                if (state.timerInterval) {
                    clearInterval(state.timerInterval);
                }
                
                // 重置所有状态
                resetToInitialState();
                
                // 更新UI
                elements.startStopBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 开始';
                elements.startStopBtn.classList.remove('btn-danger');
                elements.startStopBtn.classList.remove('btn-danger');
                elements.startStopBtn.classList.add('btn-primary');
                elements.pauseResumeBtn.disabled = true;
                elements.pauseResumeBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';
                elements.pauseResumeBtn.classList.remove('btn-primary');
                elements.pauseResumeBtn.classList.add('btn-secondary');
                elements.taskDisplay.classList.add('hidden');
                elements.sessionStats.classList.add('hidden');
                
                // 清除localStorage
                localStorage.removeItem('timerAppState');
                
                // 重新渲染任务列表和统计
                renderTasks();
                renderStats();
                
                // 显示成功提示
                showToast('所有数据已清空');
                
            } catch (error) {
                console.error('清空数据失败:', error);
                showToast('清空数据失败，请重试');
            } finally {
                // 关闭确认对话框
                closeModal(elements.clearConfirmation);
            }
        }

        // 导出数据到txt文件
        function exportData() {
            try {
                // 创建要导出的数据对象
                const dataToExport = {
                    points: state.points,
                    multiplier: state.multiplier,
                    level: state.level,
                    experience: state.experience,
                    experienceToNextLevel: state.experienceToNextLevel,
                    tasks: state.tasks,
                    projectTotalTimes: state.projectTotalTimes,
                    interestRate: state.interestRate,
                    exportTime: new Date().toISOString()
                };
                
                // 转换为JSON字符串
                const dataStr = JSON.stringify(dataToExport, null, 2);
                const dataBlob = new Blob([dataStr], { type: 'text/plain' });
                const url = URL.createObjectURL(dataBlob);
                
                // 创建下载链接
                const a = document.createElement('a');
                a.href = url;
                a.download = `timer_data_${new Date().toISOString().slice(0,10)}.txt`;
                document.body.appendChild(a);
                a.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 0);
                
                showToast('数据导出成功');
            } catch (error) {
                console.error('导出数据失败:', error);
                showToast('导出数据失败，请重试');
            }
        }

        // 从txt文件导入数据
        function importData(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const importedData = JSON.parse(e.target.result);
                    
                    // 验证导入的数据结构
                    if (typeof importedData === 'object' && 
                        'points' in importedData && 
                        'tasks' in importedData && 
                        Array.isArray(importedData.tasks)) {
                        
                        // 停止计时器
                        if (state.timerInterval) {
                            clearInterval(state.timerInterval);
                        }
                        
                        // 导入数据
                        state.points = importedData.points || 0;
                        state.multiplier = importedData.multiplier || 1.00;
                        state.level = importedData.level || 1;
                        state.experience = importedData.experience || 0;
                        state.experienceToNextLevel = importedData.experienceToNextLevel || 200;
                        state.tasks = importedData.tasks || [];
                        state.projectTotalTimes = importedData.projectTotalTimes || {};
                        state.interestRate = importedData.interestRate || 0.001;
                        state.lastPointsValue = importedData.lastPointsValue || 0;
                        state.lastPointsColor = importedData.points < 0;
                        
                        // 重置计时状态
                        state.timerRunning = false;
                        state.timerPaused = false;
                        state.elapsedTime = 0;
                        state.startTime = null;
                        state.lastSavedTime = null;
                        state.lastExperienceUpdate = 0;
                        state.previousTotalExperience = 0;
                        state.currentTask = null;
                        state.sessionExperience = 0;
                        state.sessionPoints = 0;
                        state.lastInterestCalculation = Date.now();
                        
                        // 更新倍率和利率显示
                        elements.multiplierDisplay.textContent = formatMultiplier(state.multiplier);
                        elements.interestRateDisplay.textContent = formatInterestRate(state.interestRate);
                        
                        // 更新UI
                        updateTimer();
                        elements.pointsDisplay.textContent = formatPoints(state.points);
                        // 更新颜色：只有总积分<0时才显示红色
                        updatePointsColor(state.points < 0);
                        
                        const expPercentage = Math.min(100, (state.experience / state.experienceToNextLevel) * 100);
                        elements.expBar.style.width = `${expPercentage}%`;
                        elements.levelDisplay.textContent = state.level;
                        elements.expText.textContent = `${formatExperience(state.experience)}/${formatExperience(state.experienceToNextLevel)}`;
                        elements.startStopBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 开始';
                        elements.startStopBtn.classList.remove('btn-danger');
                        elements.startStopBtn.classList.add('btn-primary');
                        elements.pauseResumeBtn.disabled = true;
                        elements.taskDisplay.classList.add('hidden');
                        elements.sessionStats.classList.add('hidden');
                        elements.currentExp.textContent = "0.00";
                        elements.currentPoints.textContent = "0.00";
                        
                        // 保存导入的数据
                        saveState();
                        
                        // 重新渲染任务列表和统计
                        renderTasks();
                        renderStats();
                        updateImportTaskSelect();
                        
                        showToast('数据导入成功');
                    } else {
                        showToast('导入的数据格式不正确');
                    }
                } catch (error) {
                    console.error('导入数据出错:', error);
                    showToast('导入失败，请检查文件格式');
                }
            };
            reader.readAsText(file);
            
            // 重置文件输入，允许重复选择同一个文件
            elements.importFile.value = '';
        }

        // 利息计算定时器，每1秒计算一次，确保稳定
        setInterval(calculateAndApplyInterest, 1000);

        // 页面关闭前保存状态
        window.addEventListener('beforeunload', saveState);

        // 事件监听
        elements.startStopBtn.addEventListener('click', () => {
            if (!state.timerRunning) {
                // 打开任务选择模态框
                renderTasks();
                openModal(elements.taskModal);
            } else {
                // 停止计时器
                stopTimer();
            }
        });

        elements.pauseResumeBtn.addEventListener('click', pauseTimer);

        elements.closeTaskModal.addEventListener('click', () => {
            closeModal(elements.taskModal);
        });

        elements.addTaskBtn.addEventListener('click', addTask);

        elements.newTaskName.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                addTask();
            }
        });

        elements.newTaskInterval.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                addTask();
            }
        });

        elements.closeResultModal.addEventListener('click', () => {
            closeModal(elements.resultModal);
            showToast('计时已完成');
        });

        // 导入时长相关事件
        elements.importTimeBtn.addEventListener('click', () => {
            // 确保任务选择框已更新
            updateImportTaskSelect();
            openModal(elements.importTimeModal);
            updateImportExperiencePreview(); // 初始化预览
        });

        elements.closeImportTimeModal.addEventListener('click', () => {
            closeModal(elements.importTimeModal);
        });

        elements.confirmImportTimeBtn.addEventListener('click', importTaskTime);

        // 任务选择变化时更新预览和任务信息
        elements.importTaskSelect.addEventListener('change', () => {
            const selectedTaskId = elements.importTaskSelect.value;
            if (selectedTaskId) {
                const selectedTask = state.tasks.find(t => t.id.toString() === selectedTaskId);
                if (selectedTask) {
                    showTaskPointsInfo(selectedTask);
                    
                    // 只有正积分任务才显示经验预览
                    if (selectedTask.value > 0) {
                        elements.importExperienceContainer.classList.remove('hidden');
                        updateImportExperiencePreview();
                    } else {
                        elements.importExperienceContainer.classList.add('hidden');
                    }
                }
            } else {
                elements.taskPointsInfo.classList.add('hidden');
                elements.importExperienceContainer.classList.add('hidden');
            }
        });

        // 跳转到创建任务
        elements.goToCreateTask.addEventListener('click', () => {
            closeModal(elements.importTimeModal);
            renderTasks();
            openModal(elements.taskModal);
            elements.newTaskName.focus();
        });

        // 监听时长输入变化，更新经验预览并验证输入
        elements.importHours.addEventListener('input', () => {
            validateImportTimeInputs();
            updateImportExperiencePreview();
        });
        
        elements.importMinutes.addEventListener('input', () => {
            validateImportTimeInputs();
            updateImportExperiencePreview();
        });
        
        elements.importSeconds.addEventListener('input', () => {
            validateImportTimeInputs();
            updateImportExperiencePreview();
        });

        // 统计相关事件
        elements.statsBtn.addEventListener('click', () => {
            renderStats();
            openModal(elements.statsModal);
        });

        elements.closeStatsModal.addEventListener('click', () => {
            closeModal(elements.statsModal);
        });

        elements.closeStatsBtn.addEventListener('click', () => {
            closeModal(elements.statsModal);
        });

        // 数据管理按钮事件
        elements.clearBtn.addEventListener('click', () => {
            openModal(elements.clearConfirmation);
        });

        elements.cancelClear.addEventListener('click', () => {
            closeModal(elements.clearConfirmation);
        });

        elements.confirmClear.addEventListener('click', clearAllData);

        elements.exportBtn.addEventListener('click', exportData);

        elements.importBtn.addEventListener('click', () => {
            elements.importFile.click();
        });

        elements.importFile.addEventListener('change', importData);

        // 初始化 - 加载保存的状态
        loadState();
        renderTasks();
    </script>
    
    </body>
</html>